<script setup>
  /**
   * & 文件引入区域
   */
  import { ToastFun } from "@/hook/toast";
  import { useUseStore } from "@/stores/user";
  import { useRoute, useRouter } from "vue-router";
  import { onBeforeMount, onUnmounted, reactive, ref } from "vue";
  import { showToast } from "vant";
  import {
    upLoadImg,
    getDealDetail,
    upLoadPointBalance,
    getTraditionDetail,
    confirmTransaction,
    generateTradeOrder,
  } from "@/server/api/userInfo";
  import { exchange } from "@/stores/exchange";
  import { getJWTFun } from "@/hook/jsrsasign";
  import { useI18n } from "vue-i18n";
  const { t } = useI18n();
  /**
   * & 变量声明区
   */
  const route = useRoute();
  const router = useRouter();
  let tradinId; // 接收订单id
  let orderData = ref(); // 订单详情数据
  let socket = null; // 准备进行长连接的变量
  let baseUrl = useUseStore().ing; // 图片拼接基础路径
  let isShow = ref(false); // 用于控制长连接前后页面的显示隐藏

  // 交易提交请求体
  let upLoadReq = reactive({
    typeId: "",
    orderId: "",
    piAddress: "",
    buyerId: useUseStore().userId,
  });

  let formData = null; // 上传交易凭证的图片数据
  let imgList = ref(); // 上传的图片回显

  let regex = /^(?!\s+$).+$/; // 交易地址正则匹配

  /**
   * & 函数区
   */
  // 获取订单详情方法   (交易所点击交易后的页面)
  const getTraditionDetailFun = async () => {
    // 轻提示，等待数据请求和长连接成功后再关闭提示
    ToastFun("Loading", { duration: 1000 });
    let { data } = await getTraditionDetail(tradinId);
    if (data.data != null) {
      ToastFun("", {});
      isShow.value = true;

      orderData.value = data.data;

      // 生成请求体
      for (const i in upLoadReq) {
        if (i in orderData.value) {
          upLoadReq[i] = orderData.value[i];
        }
      }
    } else {
      // 获取不到值则说明该交易已经有人在进行，直接退出该页面并提示
      ToastFun("", { msg: "" });
      router.back();
    }

  };

  // 交易双方获取交易详情
  const getDealDetailFun = async () => {
    ToastFun("Loading", { duration: 1000 });
    let { data } = await getDealDetail(tradinId);
    if (data.code == 200) {
      ToastFun("close", {});
      isShow.value = true;

      // 解构获取需要的对应数据
      let {
        typeId,
        status,
        imageUrl,
        sellerId,
        piBalance,
        piAddress,
        buyerName,
        sellerName,
        buyerImageUrl,
        sellerImageUrl,
        pointBalance,
      } = data.data;

      // 修改请求体
      upLoadReq.piAddress = piAddress;
      upLoadReq.orderId = tradinId;
      upLoadReq.typeId = typeId;

      orderData.value = {
        status,
        typeId,
        imageUrl,
        sellerId,
        piAddress,
        piBalance,
        pointBalance,
        userImage:
          sellerId == useUseStore().userId ? buyerImageUrl : sellerImageUrl,
        userName: sellerId == useUseStore().userId ? buyerName : sellerName,
      };

    } else {
      ToastFun("", {});
      router.back();
    }
  };

  // 提交订单方法
  const submit = () => {
    generateTradeOrderFun(); // 生成订单
  };

  // 生成订单
  const generateTradeOrderFun = async () => {

    ToastFun("Loading", { duration: 1000 });

    // 发起请求
    let { data } = await generateTradeOrder(tradinId, useUseStore().userId);

    // 提示交易成功，并且返回上一级
    if (data.code == 200) {
      showToast('请点击右上角头像，进入订单完成流程');
      // router.back();
      setTimeout(() => {
        router.go(-1);
      }, 1000)
    } else {
      ToastFun("", {})
    }
  };

  // 提交转积分
  const upPointFun = async () => {
    // 判断输入的地址是否有误
    if (!regex.test(upLoadReq.piAddress) || upLoadReq.piAddress == null || upLoadReq.piAddress == "") {
      upLoadReq.piAddress = "";
      ToastFun("show", { msg: t("item.details.WalletAddressError") });
      return;
    }

    ToastFun("Loading", { duration: 1000 });
    let token = getJWTFun(upLoadReq); // 生成tokken
    let { data } = await upLoadPointBalance(token); // 请求接口

    if (data.code == 200) {
      // 提示交易成功，并且返回上一级
      ToastFun("", {});
      getDealDetailFun();
    } else {
      ToastFun("", {});
    }
  };

  // 提交pi币转账凭证
  const upLoadImgFun = async () => {
    if (formData != null) {
      let { typeId, orderId } = upLoadReq;

      let Req = {
        typeId,
        orderId,
        userId: useUseStore().userId,
      };

      // 轻提示
      ToastFun("Loading", { duration: 1000 });
      let token = getJWTFun(Req); // 生成tokken
      let { data } = await upLoadImg(token, formData); // 请求接口

      if (data.code == 200) {
        ToastFun("", {});

        // 判断如果是卖家确认要上传pi支付凭证，则重新请求数据
        if (exchange().orderType == "comfirm") {
          // 重新获取该订单详情
          getDealDetailFun();
        } else if (exchange().orderType == "transaction") {
          router.back();
        }
      } else {
        ToastFun("", {});
      }
    } else {
      ToastFun("show", { msg: t("exchangeOrder.pic") });
    }
  };

  // 确认交易
  const confirmTransactionFun = async () => {
    ToastFun("Loading", { duration: 1000 });

    // 生成token
    let token = getJWTFun({
      userId: useUseStore().userId,
      orderId: tradinId,
    });

    // 请求接口
    let { data } = await confirmTransaction(token);

    if (data.code == 200) {
      ToastFun("", {});

      // 成功后重新获取订单详情
      getDealDetailFun();

    } else {
      ToastFun("", {});
    }
  };

  // 获取图片
  const getImg = (file) => {
    // 转换表单格式
    formData = new FormData();
    formData.append("file", file.file);
  };

  // 图片超过上传大小限制提示
  const onOversize = () => {
    ToastFun("show", { msg: t("exchangeOrder.over") });
  };

  // 生命周期
  onBeforeMount(() => {
    tradinId = route.query.id; // 获取订单id
    if (exchange().orderType == "transaction") {
      getTraditionDetailFun(); // 获取订单详情方法
    } else if (exchange().orderType == "comfirm") {
      getDealDetailFun(); // 交易双方获取交易详情
    }
  });

  onUnmounted(() => {
    // 退出页面关闭socket
    if (socket != null) {
      socket.close();
    }
  });
</script>

<template>
  <div class="ExchangeOrderPage" v-if="isShow">
    <div class="top">
      <ExchangeOrderTop :title="$t('exchange.trade')" />
    </div>
    <!-- 已经生成了订单，订单表有数据就显示订单 -->
    <div class="content" v-if="orderData">
      <div class="user">
        <img :src="orderData.userImage || '/images/pipayshop_logo.png'" alt="" />
        <div class="name">{{ orderData.userName }}</div>
      </div>

      <div class="form">
        <div class="item to">
          <!-- 0 pi换积分 1 积分换pi -->
          <!-- 换积分且卖家是自己 换Pi且卖家不是自己 -->
          <!-- tip1需要向对方支付  tips2可以从对方获得 -->
          <div class="title">
            {{
            (orderData.typeId == 0 &&
            orderData.sellerId == useUseStore().userId) ||
            (orderData.typeId == 1 &&
            orderData.sellerId != useUseStore().userId)
            ? $t("exchange.tips1")
            : $t("exchange.tips2")
            }}
          </div>
          <div class="num">
            <div class="title">Pi</div>
            <span>{{ orderData.piBalance }}</span>
          </div>
        </div>

        <div class="item from">
          <!-- 0 pi换积分 1 积分换pi -->
          <div class="title">
            {{
            (orderData.typeId == 0 &&
            orderData.sellerId != useUseStore().userId) ||
            (orderData.typeId == 1 &&
            orderData.sellerId == useUseStore().userId)
            ? $t("exchange.tips1")
            : $t("exchange.tips2")
            }}
          </div>
          <div class="num">
            <div class="title">eCNY</div>
            <span>{{ orderData.pointBalance }}</span>
          </div>
        </div>
      </div>
      <!-- 用户进入订单变成transaction 点击确认之后，订单的状态变成confirm  -->
      <!-- 订单状态为0:开始交易 1:提交积分/地址 -->
      <div class="address" v-if="exchange().orderType == 'comfirm' && orderData.status < 2">
        <!-- “钱包地址” -->
        <div class="title" v-if="orderData.status < 2">
          {{ $t("exchange.address") }}
        </div>
        <!-- 提交钱包地址 -->
        <input type="text" class="text" v-model="upLoadReq.piAddress" v-if="orderData.typeId == 0 &&
    orderData.status == 0 &&
    orderData.sellerId != useUseStore().userId
    " />

        <div class="text" v-if="(orderData.typeId == 0 &&
    orderData.status == 1 ) ||
    (orderData.typeId == 1 &&
      orderData.status == 1 &&
      orderData.sellerId != useUseStore().userId)
    ">
          {{ orderData.piAddress }}
        </div>
      </div>
      <!-- 已经提交了积分并且comfirm:
                                    （pi换积分卖家是自己）或者（积分换pi，查看人不是交易发起者 页面提示上传凭证） -->
      <div class="voucher" v-if="orderData.status == 1 && exchange().orderType == 'comfirm'">
        <div class="title" v-if="(orderData.typeId == 0 &&
    orderData.sellerId == useUseStore().userId) ||
    (orderData.typeId == 1 &&
      orderData.sellerId != useUseStore().userId)
    ">
          {{ $t("exchange.certificate") }}
        </div>
        <!-- （pi换积分 并且卖家是自己并且图片是空）或者（积分换pi，卖家不是自己，图片为空） -->
        <van-uploader :max-count="1" v-model="imgList" :after-read="getImg" @oversize="onOversize"
          @delete="formData = null" :max-size="1000 * 1024" v-if="(orderData.typeId == 0 &&
    orderData.sellerId == useUseStore().userId &&
    !orderData.imageUrl) ||
    (orderData.typeId == 1 &&
      orderData.sellerId != useUseStore().userId &&
      !orderData.imageUrl)
    ">
          <div class="updata">
            <img src="/images/Me/updataLogo.png" alt="" class="icon" />
            <span>Photos</span>
          </div>
        </van-uploader>

        <!-- <div class="question" v-if="false">
          <textarea name="" id="" cols="30" rows="5" :placeholder="$t('exchangeOrder.issuse')" />
          <van-uploader>
            <div class="updata">
              <img src="/images/Me/updataLogo.png" alt="" class="icon" />
              <span>Photos</span>
            </div>
          </van-uploader>
        </div> -->
      </div>

      <!-- 交易凭证图片 -->
      <div class="img" v-if="orderData.imageUrl">
        <div class="title">{{ $t("exchange.certificate") }}</div>
        <img style="width: 311px;height:652px ;object-fit: contain;" :src="orderData.imageUrl" />
      </div>
    </div>
    <!-- 一开始只会显示要用户确认要进行交易的按钮 -->
    <div class="submit" @click="submit" v-if="exchange().orderType == 'transaction'">
      {{ $t("exchange.confirm") }}
    </div>
    <!--  submit1 提交积分  waiting1 等待对方提交凭证
          订单状态为交易中并且已经在前端标记为了comfirm  comfirm是形成了订单了
        订单的卖家不是现在登录的用户，点击按钮就判断pi地址是否有错
        卖家不是现在的用户
      -->
    <div class="submit" @click="orderData.sellerId != useUseStore().userId ? upPointFun() : ''"
      v-if="orderData.status == 0 && exchange().orderType == 'comfirm'">
      {{
      orderData.sellerId != useUseStore().userId
      ? $t("exchange.submit1")
      : $t("exchange.waiting1")
      }}
    </div>
    <!-- 
  点击事件：如果是pi换积分以及卖家是登录的用户）或者（积分换pi以及卖家不是现在的用户）true的话，就触发提交凭证的方法
  v-if:如果订单的状态是1(提交积分)且是comfirm 
       则：1.(pi换积分，订单卖家是现在用户)或者(订单是积分换pi 且登录不是卖家账号 显示 上传凭证)
           2.否则等待上传凭证
 -->
    <div class="submit" @click="
    (orderData.typeId == 0 && orderData.sellerId == useUseStore().userId) ||
      (orderData.typeId == 1 && orderData.sellerId != useUseStore().userId)
      ? upLoadImgFun()
      : ''
    " v-if="orderData.status == 1 && exchange().orderType == 'comfirm'">
      {{
      (orderData.typeId == 0 && orderData.sellerId == useUseStore().userId) ||
      (orderData.typeId == 1 && orderData.sellerId != useUseStore().userId)
      ? $t("exchange.submit2")
      : $t("exchange.waiting2")
      }}
    </div>
    <!-- 订单状态为 已经上传凭证 并且是comfirm显示此框
     点击事件：（Pi换积分，卖家不是现在的账号） 或者 （积分换pi卖家是自己）触发交易事件
              
    confirm确认
    waiting3等待对方确认交易-->
    <div class="submit" v-if="orderData.status == 2 && exchange().orderType == 'comfirm'" @click="
    (orderData.typeId == 0 && orderData.sellerId != useUseStore().userId) ||
      (orderData.typeId == 1 && orderData.sellerId == useUseStore().userId)
      ? confirmTransactionFun()
      : ''
    ">
      {{
      (orderData.typeId == 0 && orderData.sellerId != useUseStore().userId) ||
      (orderData.typeId == 1 && orderData.sellerId == useUseStore().userId)
      ? $t("exchange.confirm")
      : $t("exchange.waiting3")
      }}
    </div>
    <!-- 订单完成了3 waiting4订单完成 -->
    <div class="submit" v-if="orderData.status == 3 && exchange().orderType == 'comfirm'">
      {{ $t("exchange.waiting4") }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .ExchangeOrderPage {
    position: relative;
    min-height: 100vh;
    max-height: 100vh;
    overflow: scroll;

    &::-webkit-scrollbar {
      display: none;
    }

    >.content {
      padding: 24rem 16rem 80rem;

      >.user {
        display: flex;
        align-items: center;

        margin-bottom: 16rem;

        >img {
          width: 34rem;
          margin-right: 6rem;
        }

        >.name {
          color: #333;
          font-size: 16rem;
          font-weight: 500;
          line-height: 22rem;
        }
      }

      >.form {
        position: relative;

        >.item {
          margin-bottom: 24rem;

          >.title {
            font-size: 14rem;
            font-weight: 400;
            line-height: 20rem;
            color: #333;
            margin-bottom: 24rem;
          }

          >.num {
            line-height: 44rem;
            font-size: 32rem;
            font-weight: 500;

            display: flex;

            >.title {
              color: rgba(100, 46, 142, 1);
              margin-right: 10rem;
            }

            >span {
              color: rgba(51, 51, 51, 1);
            }
          }

          &.from {
            >.num .title {
              font-size: 16rem;
              font-weight: 400;
              line-height: 44rem;
            }
          }
        }
      }

      >.address {
        font-size: 16rem;
        font-weight: 400;
        line-height: 22rem;

        >div {
          margin-bottom: 16rem;
        }

        >input {
          width: 100%;
          border-bottom: 1rem solid #f0f0f0;
        }
      }

      >.voucher {
        font-size: 16rem;
        font-weight: 400;
        line-height: 22rem;

        >.title {
          margin-bottom: 24rem;
        }

        >.question {
          position: relative;
          border-radius: 16rem;
          padding: 12rem;
          background: #f5f5f5;

          >textarea {
            width: 100%;
            border: 0;
            background: transparent;
          }
        }

        .updata {
          width: 64rem;
          height: 64rem;

          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          font-size: 14rem;
          line-height: 20rem;
          color: rgba(255, 255, 255, 1);

          border-radius: 4rem;
          background: #ccc;

          >img {
            width: 14rem;
          }
        }
      }

      >.img {
        width: 100%;

        >.title {
          font-size: 16rem;
          font-weight: 400;
          line-height: 22rem;
          margin-bottom: 16rem;
        }

        img {
          width: 100%;
        }
      }
    }

    >.submit {
      position: fixed;
      bottom: 16rem;
      left: 0;
      right: 0;

      display: flex;
      justify-content: center;
      margin: 0 16rem;
      padding: 15rem 0;
      background: #642e8e;
      border-radius: 26rem;

      font-size: 16rem;
      font-weight: 500;
      line-height: 22rem;
      color: #fff;
    }
  }
</style>